package com.example.yangchunxi2022090658

import android.content.ClipData.Item
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.contract.ActivityResultContract
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

class ActivityParam(){
    public var paramName:String? = null
    public var paramVal:String? = null
    constructor(paramName:String,paramVal:String):this(){
        this.paramName = paramName
        this.paramVal = paramVal
    }
}
class ConTrack(): ActivityResultContract<String, String>(){
    private var params = ArrayList<ActivityParam>(0)
    private var target :Class<*>? = null
    constructor(targetActivity:Class<*>,vararg params :ActivityParam):this(){
        for (param in params){
            this.params.add(param)
        }
        target = targetActivity
    }
    fun addParam(param:ActivityParam){
        params.add(param)
    }
    override fun createIntent(context: Context, input: String): Intent {
        if (target ==null){
            throw Exception("目标Activity不能为空")
        }
        val intentInstance = Intent(context,target).apply {
            for (param in params){
                putExtra(param.paramName,param.paramVal)
            }
            putExtra("Input",input)
        }


        return intentInstance
    }

    override fun parseResult(resultCode: Int, intent: Intent?): String {

        return intent?.getStringExtra("result") ?: ""
    }

}

class StuAdapter(private val stuList: List<Stu>) : RecyclerView.Adapter<StuAdapter.StuViewHolder>() {

    class StuViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvText: TextView = itemView.findViewById(R.id.tv_text)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StuViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.stu, parent, false)
        return StuViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: StuViewHolder, position: Int) {
        val currentStu = stuList[position]
        holder.tvText.text = currentStu.toString()
    }

    override fun getItemCount(): Int {
        return stuList.size
    }
}
class MainActivity : AppCompatActivity() {
    val stuList = MutableList<Stu>(0,{index->Stu("","","","")})
    private fun bindToActivityEx(id:Int, activity:Class<*>, callback: ActivityResultCallback<String>, vararg params :ActivityParam){
        val btn = this.findViewById<Button>(id)
        val lunchar = registerForActivityResult(ConTrack(activity,*params),callback)
        btn.setOnClickListener {
            lunchar.launch("Hello")
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        try {
            val file = openFileInput("student.json")
            val listType: java.lang.reflect.Type = object : TypeToken<ArrayList<Stu>>() {}.type
            // 读取文件内容并解析为 ArrayList<Stu>
            val temp = Gson().fromJson<List<Stu>>(file.reader(), listType)
            for(item in temp){
                println(item)
                stuList.add(item)
            }

        }
        catch (e: Exception){
            e.printStackTrace()
        }
        val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(this)


        var stuAdapter = StuAdapter(stuList)
        recyclerView.adapter = stuAdapter
        bindToActivityEx(R.id.button,addStudent::class.java,{
            result->
            stuAdapter= StuAdapter(stuList)
            recyclerView.adapter = stuAdapter
            stuList.add(Gson().fromJson(result,Stu::class.java))
            try {

                val temp = Gson().toJson(stuList)
                openFileOutput("student.json", Context.MODE_PRIVATE).use {
                    it.write(temp.toByteArray())
                }
            }
            catch (e: Exception){

            }

         },ActivityParam("name","这是一个参数"))

    }
}